package org.peterf.foxish.program;

import org.peterf.foxish.opengl20.OpenGLUtil;
import org.peterf.foxish.util.ResourceUtil;

import android.opengl.GLES20;

/**
 * Class representing a fragment shader. Remember to call
 * {@link #delete(FragmentShader)} to release unused shader.
 * 
 * @author peter
 * 
 */
public class FragmentShader {

    public static FragmentShader compile(int resId) {
        String source = ResourceUtil.getString(resId);
        return compile(source);
    }

    /**
     * Compile a fragment shader directly from the string source. The returned
     * fragment shader should be deleted by user once it is not needed.
     * 
     * @param source
     *            The source code.
     * @return The shader. null if the compilation fails. Upon failure, nothing
     *         needs to be deleted.
     */
    public static FragmentShader compile(String source) {
        // TODO Remove GLES20 related.
        int shader = OpenGLUtil
                .compileShader(GLES20.GL_FRAGMENT_SHADER, source);
        if (shader == 0) {
            return null;
        } else {
            return new FragmentShader(shader);
        }
    }

    /**
     * Delete a useless fragment shader.
     * 
     * @param shader
     *            The shader to be deleted.
     */
    public static void delete(FragmentShader shader) {
        OpenGLUtil.deleteShader(shader.name);
    }

    /* package */int name;

    private boolean valid = true;

    private FragmentShader(int name) {
        this.name = name;
    }

    public void invalidate() {
        valid = false;
    }

    public boolean isValid() {
        return valid;
    }

    /* package */void recompile(int resId) {
        String source = ResourceUtil.getString(resId);
        recompile(source);
    }

    /* package */void recompile(String source) {
        name = OpenGLUtil.compileShader(GLES20.GL_FRAGMENT_SHADER, source);
        valid = true;
    }

}
